using LiJ.Common.Core.Utils;
using System;
using System.IO;
using System.Text;

namespace LiJ.Common.Plugs.LogPlug
{
	/// <summary>
	/// 系统默认写日志模块
	/// </summary>
	public class DefaultLogPlug : ILogPlug
	{
		private readonly string _logBaseDirPath;

		private const string LogFormat = "{0:T}    Code:{1}    Key:{2}   Detail:{3}";

		private readonly object _obj = new object();

		/// <summary>
		/// 构造函数
		/// </summary>
		public DefaultLogPlug()
		{
            _logBaseDirPath = Path.Combine(AppContext.BaseDirectory, "log");
			if (!Directory.Exists(_logBaseDirPath))
			{
				Directory.CreateDirectory(_logBaseDirPath);
			}
		}

		private string GetLogFilePath(string module, LogLevelEnum level)
		{
			string text = string.Format("{0}\\{1}\\{2}\\", this._logBaseDirPath, module, level);
			if (!Directory.Exists(text))
			{
				Directory.CreateDirectory(text);
			}
			return text + DateTime.Now.ToString("yyyyMMddHH") + ".txt";
		}

		/// <summary>
		/// 写日志
		/// </summary>
		/// <param name="info"></param>
		public void WriteLog(LogInfo info)
		{
			lock (_obj)
			{
				using (StreamWriter streamWriter = new StreamWriter(new FileStream(this.GetLogFilePath(info.ModuleName, info.Level), FileMode.Append, FileAccess.Write), Encoding.UTF8))
				{
					streamWriter.WriteLine("{0:T}    Code:{1}    Key:{2}   Detail:{3}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), info.LogCode, info.MsgKey, info.Msg);
				}
			}
		}

		/// <inheritdoc />
		/// <summary>
		/// 生成错误编号
		/// </summary>
		/// <returns></returns>
		public void SetLogCode(LogInfo log)
		{
			log.LogCode = NumUtil.TimeMilliNum().ToCode();
		}
	}
}
